package net.chinatax.rz.zzs;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Tools {
	//配置文件名称
	public static final String CONFIGFILENAME ="rz_dir.properties";
	
	//配置文件键名
	public static final String ZZSINPUT = "ZZSINPUT";
	public static final String ZZSOUTPUT = "ZZSOUTPUT";
	
	//发票认证结果信息类
	public static final class FP{
		public static final String FPDM = "fpdm";
		public static final String FPHM = "fphm";
		public static final String RZJG_DM = "rzjg_dm";
		public static final String RZJG_MC = "rzjg_mc";
	}
	//配置文件键值对
	public static Map pathMap = null;
	static {
		if(pathMap == null){
			pathMap = getProperties(Tools.class.getResource("").getPath()+File.separator+Tools.CONFIGFILENAME);
		}
	}
	public static void main(String[] args){
	
		System.out.println(pathMap);
	}
    //批量写入properties信息
    public static void writeAllProperties(File file, Map map) {
        Properties properties = new Properties();
        try {
            //将文件读入流
            InputStream inputStream = new FileInputStream(file);
            //加载文件
            properties.load(inputStream);
            //准备写入�?
            OutputStream outputStream = new FileOutputStream(file);
            
            System.out.println(file.getAbsolutePath()+""+map);
            //将信息放入Properites
            //properties.put("11", 123445);
            Set set = map.keySet();
            for(Iterator i = set.iterator();i.hasNext();){
            	Object key = i.next();
            	properties.put(key.toString(), map.get(key)==null?"":map.get(key));
            }
            //保存此Properites
            properties.store(outputStream, "Update '");
            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //批量写入properties信息
    public static void writeAllProperties(String filePath, Map map) {
    	writeAllProperties(new File(filePath),map);
    }
    //读取属性文件信息
    public static Map getProperties(String fileName){
    	return getProperties(new File(fileName));
    }
    //读取属性文件信息
    public static Map getProperties(File file) {
    	Map map = new HashMap(2);
        Properties properties = new Properties();
        try {
            //将文件读入流
            InputStream inputStream = new FileInputStream(file);
            //加载文件
            properties.load(inputStream);
            Set set =properties.keySet();
            
            for(Iterator i = set.iterator();i.hasNext();){
            	Object key = i.next();
            	map.put(key, properties.get(key));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 去除list中内容重复的元素
     */
    public static List getDistinctList(List list) {
        Map temp = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            temp.put(list.get(i), list.get(i));
        }
        Set set = temp.keySet();
        List l = new LinkedList();
        for (Iterator iterator = set.iterator(); iterator.hasNext();) {
            l.add(iterator.next());
        }
        return l;
    }

    // 复制文件
    public static void copyFile(File sourceFile, File targetFile)
            throws IOException {
        // 新建文件输入流并对它进行缓冲
        FileInputStream input = new FileInputStream(sourceFile);
        BufferedInputStream inBuff = new BufferedInputStream(input);

        // 新建文件输出流并对它进行缓冲
        FileOutputStream output = new FileOutputStream(targetFile);
        BufferedOutputStream outBuff = new BufferedOutputStream(output);

        // 缓冲数组
        byte[] b = new byte[1024 * 5];
        int len;

        while ((len = inBuff.read(b)) != -1) {
            outBuff.write(b, 0, len);
        }

        // 刷新此缓冲的输出�?
        outBuff.flush();
        System.out.println("添加文件" + targetFile);
        //关闭�?
        inBuff.close();
        outBuff.close();
        output.close();
        input.close();
    }
    private static java.util.Random ran = new java.util.Random(Integer.MAX_VALUE);
    
    //获取唯一序列
    public final static String UID(String seed){
    	System.out.println(seed);
    	return seed+"_"+System.currentTimeMillis();
    }
    public final static void writeToFile(String filepath, String content) {
        try {
            File f = new File(filepath);
            File dir = new File(filepath.substring(0, filepath.lastIndexOf(File.separator)));
            try {
                if (!dir.exists()) dir.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                if (!f.exists())
                    f.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }


            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filepath), "UTF-8")));
            out.print(content);
            out.flush();
            out.close();
        } catch (IOException e) {
            System.out.println("生成失败");
            e.printStackTrace();
        }
    }

    // 复制文件�?
    public static void copyDirectiory(String sourceDir, String targetDir) {
        // 新建目标目录

        delAllFile(targetDir);

        // 获取源文件夹当前下的文件或目�?
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                // 源文�?
                File sourceFile = file[i];
                // 目标文件
                File targetFile = new
                        File(new File(targetDir).getAbsolutePath()
                        + File.separator + file[i].getName());
                String fileName = null;
                try {
                    fileName = targetFile.getCanonicalPath();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                File dir = new File(fileName.substring(0, fileName.lastIndexOf(File.separator)));
                try {
                    if (!dir.exists()) dir.mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    if (!targetFile.exists())
                        targetFile.createNewFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    copyFile(sourceFile, targetFile);
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
            if (file[i].isDirectory()) {
                // 准备复制的源文件�?
                String dir1 = sourceDir + File.separator + file[i].getName();
                // 准备复制的目标文件夹
                String dir2 = targetDir + File.separator + file[i].getName();
                copyDirectiory(dir1, dir2);
            }
        }
    }

    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内�?
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下�?��文件
    //param path 文件夹完整绝对路�?
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                try {
                    System.out.println("删除文件" + temp.getCanonicalPath());
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文�?
                delFolder(path + "/" + tempList[i]);//再删除空文件�?
                flag = true;
            }
        }
        return flag;
    }

    /**
     * MD5 加密算法
     *
     * @param str
     * @return
     */
    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }

        return md5StrBuff.toString();
    }

    /**
     * 得到网页数据的编码方�?
     */
    public static String getCharSet(String html) {

        List list = new ArrayList();
        Pattern pattern;

        pattern = Pattern.compile("charset=[a-z0-9A-Z-]+\"");
        Matcher matcher = pattern.matcher(html);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            String temp = matcher.group();
            buffer.append(temp);
            if (!temp.equals("")) {
                list.add(temp);
            }
            buffer.append("\r\n");
            System.out.println(buffer.toString());
        }

        //去掉charset=GBK"中的charset=�?字符
        return ((String) list.get(0)).replaceAll("charset=", "").replaceAll("\"", "");
    }

    /**
     * 把Map中写入属性文件中
     *
     * @param map
     * @param file
     */
    public void writeMapToProperties(Map map, String file) {
        file = this.getClass().getClassLoader().getResource("").toString() + file;
        File f = new File(file);
        BufferedWriter output = null;
        try {
            output = new BufferedWriter(new FileWriter(f));
            Set set = map.keySet();
            for (Iterator iterator = set.iterator(); iterator.hasNext();) {
                String key = (String) iterator.next();
                output.write(key + "=" + map.get(key) + "\n");
            }
            output.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public static String getCotentFromFileT(String filePath) {
        String rtn = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
            String temp = br.readLine();
            while (temp != null) {
                rtn += temp.trim();
                temp = br.readLine();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return rtn;
    }

    public static String getCotentFromFile(String filePath) {
        String rtn = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
            String temp = br.readLine();
            while (temp != null) {
                rtn += temp.trim();
                temp = br.readLine();
            }

            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return rtn;
    }


}
